package com.hs.mod_archive.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.hs.framework.base.BaseDataBindFragment
import com.hs.framework.toast.TipsToast
import com.hs.mod_archive.R
import com.hs.mod_archive.databinding.DialogEditArchiveBinding
import com.hs.mod_archive.databinding.FragmentArchiveTypeManagementBinding
import com.hs.mod_archive.helper.ArchiveTypeManagerHelper
import com.hs.mod_archive.helper.ArchiveTypeManagerHelper.OnItemClickListener
import com.hs.mod_archive.helper.ListViewHelper
import com.hs.mod_archive.helper.ListViewHelper.Companion.perPageCount
import com.hs.mod_archive.view.DialogUtil
import com.hs.mod_archive.view.MyDialog
import com.hs.room.model.archive.ArchiveType
import com.hs.room.repository.service.IArchiveDictRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class FragmentArchiveTypeManagement : BaseDataBindFragment<FragmentArchiveTypeManagementBinding>() {

    @Inject
    lateinit var service: IArchiveDictRepository

    private var types: List<ArchiveType>? = null
    var mDialog: MyDialog? = null
    lateinit var helper: ArchiveTypeManagerHelper
    var dialogBinding: DialogEditArchiveBinding? = null
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding!!.btAdd.setOnClickListener { showDialogEdit(null) }
        helper =
            ArchiveTypeManagerHelper(mBinding!!.footPageListView, object : OnItemClickListener {
                override fun onItemClickEdit(entity: ArchiveType?, position: Int) {
                    showDialogEdit(entity)
                }

                override fun onItemClickDelete(entity: ArchiveType?, position: Int) {
                    del(entity!!)
                }
            }, object : ListViewHelper.FootSearchCallback {
                override fun onActionSearch(i: Int) {
                    goPage(i)
                }
            })


    }

    private fun goPage(i: Int) {
        lifecycleScope.launch {
            service.getType(i, perPageCount).collect {
                types = it
                helper.setListDataAndRefresh(it)
            }
        }
    }

    private fun del(d: ArchiveType) {
        lifecycleScope.launch {
            service.delete(d)
            TipsToast.showTips("删除成功")
        }
    }


    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            val count: Int = service.countType()
            if (count < 1) {
                val arrayList = ArrayList<ArchiveType>()
                resources.getStringArray(R.array.archiveType).forEach { i ->
                    run {
                        val item = ArchiveType(0, 0, i, "", 0, "", true)
                        service.insert(item);
                        arrayList.add(item)
                    }
                }
                helper.setFootValue(arrayList.size, 0)
            } else {
                helper.setFootValue(count, 0)
            }

        }
        goPage(0)
    }

    private fun showDialogEdit(mArchiveType: ArchiveType?) {

        //-------------------------
        if (null == dialogBinding) {
            dialogBinding = DialogEditArchiveBinding.inflate(layoutInflater)
        }
        dialogBinding!!.tvTitle.setText(R.string.addType)
        dialogBinding!!.btSubmit.setOnClickListener { _ ->
            val name: String = dialogBinding!!.etNameOfValue.text.toString().trim()
            if (TextUtils.isEmpty(name)) {
                TipsToast.showTips("请输入有效的名称")
                return@setOnClickListener
            }
            val ob: Boolean =
                dialogBinding!!.spinnerEnable.selectedItemPosition == 0
            submitName(
                mArchiveType,
                name,
                dialogBinding!!.etRemark.text.toString().trim(), ob
            )
        }
        val root: ConstraintLayout = dialogBinding!!.getRoot()
        val parent = root.parent
        if (null != parent) {
            val viewGroup = parent as ViewGroup
            viewGroup.removeView(root)
            dialogBinding!!.etNameOfValue.setText("")
            dialogBinding!!.spinnerEnable.setSelection(0)
            dialogBinding!!.etRemark.setText(null)
        }
        if (null != mArchiveType) {
            dialogBinding!!.etNameOfValue.setText(mArchiveType!!.atName)
            dialogBinding!!.etRemark.setText(mArchiveType.atRemarks)
            if (mArchiveType.enable) {
                dialogBinding!!.spinnerEnable.setSelection(0)
            } else {
                dialogBinding!!.spinnerEnable.setSelection(1)
            }
        }
        dialogBinding!!.tvTitle.setText(if (null != mArchiveType) R.string.edit else R.string.add)
        dialogBinding!!.tvNameOf.setText(R.string.name)
        dialogBinding!!.btClose.setOnClickListener { _ -> dismissDialogEdit() }
        dialogBinding!!.btCancel.setOnClickListener { _ -> dismissDialogEdit() }
        //-------------------------
        val w = resources.getDimensionPixelSize(R.dimen.dp_582)
        val h = resources.getDimensionPixelSize(R.dimen.dp_382)
        mDialog = DialogUtil.buildSpecialView(activity, root, w, h, false, false)
    }

    fun dismissDialogEdit() {
        mDialog?.dismiss()
        mDialog = null
        dialogBinding = null
    }

    private fun submitName(
        src: ArchiveType?,
        name: String,
        remark: String,
        enabled: Boolean
    ) {
        // 编辑已有的
        if (null != src) {
            if (name != src.atName) {
                for (entity in types!!) {
                    // 同名更新 删除 替换
                    if (name == entity.atName) {
                        TipsToast.showTips("名称已存在，请重新输入")
                        return
                    }
                }
            }
            src.atName = name
            src.atRemarks = remark
            src.enable = enabled
            update(src)
        } else {
            if (null != types) {
                for (entity in types!!) {
                    if (name == entity.atName) {
                        TipsToast.showTips("名称已存在，请重新输入")
                        return
                    }
                }
            }
            var fileType =
                ArchiveType(0, 0, name, remark, 0, "", enabled)
            insert(fileType)
        }
        dismissDialogEdit()
    }

    fun update(src: ArchiveType) {
        lifecycleScope.launch {
            service.update(src)
        }
    }

    fun insert(src: ArchiveType) {
        lifecycleScope.launch {
            service.insert(src)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        helper.onDestroyView()
    }
}
